package org.readium.r2.testapp.login

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import org.readium.r2.testapp.MainActivity
import org.readium.r2.testapp.sign_up.SignUpActivity
import org.readium.r2.testapp.R


class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.log_in)

        /*登录信息*/
        val usernameEditText = findViewById<EditText>(R.id.username)
        val passwordEditText = findViewById<EditText>(R.id.password)
        val loginButton = findViewById<Button>(R.id.login_button)
        val savedusername = getSavedUsername()
        val savedpassword = getSavedPassword()
        loginButton.setOnClickListener {
            val username = usernameEditText.text.toString()
            val password = passwordEditText.text.toString()

            // 这里添加实际的登录逻辑
            if (savedusername == username && savedpassword == password) { // 示例登录凭据
                navigateToMainActivity()
            } else {
                if(savedusername != username){
                    Toast.makeText(this, "用户名错误，请重试。", Toast.LENGTH_SHORT).show()
                }
                else if(savedpassword != password){
                    Toast.makeText(this, "密码错误，请重试。", Toast.LENGTH_SHORT).show()
                }
            }
        }

        /*点击注册*/
        // 获取 logout_button
        val logoutButton: Button = findViewById(R.id.logout_button)

        // 设置点击事件监听器
        logoutButton.setOnClickListener {
            // 跳转到 SignUpActivity
            navigateToSignUpActivity()
        }
    }

    private fun getSavedUsername(): String? {
        val sharedPreferences = getSharedPreferences("UserCredentials", Context.MODE_PRIVATE)
        return sharedPreferences.getString("username", null)
    }

    private fun getSavedPassword(): String? {
        val sharedPreferences = getSharedPreferences("UserCredentials", Context.MODE_PRIVATE)
        return sharedPreferences.getString("password", null)
    }

    private fun navigateToMainActivity() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish() // 关闭当前 Activity
    }

    private fun navigateToSignUpActivity() {
        // 创建 Intent 来启动 SignUpActivity
        val intent = Intent(this, SignUpActivity::class.java)
        startActivity(intent)
        // 如果您希望在跳转后关闭当前 Activity，可以调用 finish()
        finish()
    }
}